package com.laikan.reader.core.view;

import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import com.socks.library.KLog;

/**
 * Created by admin on 2016/11/5.
 * 处理web页顶部轮播图与下拉刷新冲突
 */
public class CustomSwipeRefreshLayout extends SwipeRefreshLayout {

    // 是否存在左右滑动事件
    private boolean mDragger;
    // 记录手指按下的位置
    private float mStartY, mStartX;
    // 出发事件的最短距离
    private int mTouchSlop;

    private ScrollViewListener scrollViewListener = null;

    public CustomSwipeRefreshLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        switch (action) {
        case MotionEvent.ACTION_DOWN:
            mStartY = ev.getY();
            mStartX = ev.getX();
            //初始化左右滑动事件为false
            mDragger = false;
            break;
        case MotionEvent.ACTION_MOVE:
            //如果左右滑动事件为true  直接返回false 不拦截事件
            if (mDragger) {
                return false;
            }

            // 获取当前手指位置
            float endY = ev.getY();
            float endX = ev.getX();
            float distanceX = Math.abs(endX - mStartX);
            float distanceY = Math.abs(endY - mStartY);

            // 如果X轴位移大于Y轴距离，那么将事件交给其他控件
            if (distanceX > mTouchSlop && distanceX > distanceY) {
                mDragger = true;
                return false;
            }
            break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_CANCEL:
            //初始化左右滑动事件为false
            mDragger = false;
            break;
        }
        return super.onInterceptTouchEvent(ev);
    }

    public void setScrollViewListener(ScrollViewListener scrollViewListener) {
        this.scrollViewListener = scrollViewListener;
    }

    @Override
    protected void onScrollChanged(int x, int y, int oldx, int oldy) {
        super.onScrollChanged(x, y, oldx, oldy);
        KLog.e(" ScrollViewListener y : " + y);
        if (scrollViewListener != null) {
            scrollViewListener.onScrollChanged(this, x, y, oldx, oldy);
        }
    }

    public interface ScrollViewListener {
        void onScrollChanged(CustomSwipeRefreshLayout customSwipeRefreshLayout, int x, int y, int oldx, int oldy);

    }
}
